<?php

namespace App\Services\Com;

use App\Models\Common\EmailLog;
use Illuminate\Support\Facades\Mail;

class EmailService
{
    public static function send($to, $message_text, $param=[], $subject='MIGO', $type=1, $templateCode=''){
        try {
            switch ($type){
                case 1:
                    Mail::raw($message_text, function ($message) use($to, $subject){
                        $message->subject($subject);
                        $message->to($to);
                    });
                    break;
                case 2:
                    Mail::send($message_text, $param, function($message) use ($to, $subject){
                        $message ->to($to)->subject($subject);
                    });
                    break;
                default:
                    throw new \Exception('发送方式有误~');
            }


            EmailLog::create([
                'email' => $to,
                'param' => $message_text,
                'template_code' => $templateCode,
                'result_code' => count(Mail::failures()) >= 1 ? 'fail' : 'success',
            ]);

            if(count(Mail::failures()) >= 1) throw new \Exception('发送失败！');
        }catch (\Exception $e){
            throw new \Exception($e->getMessage());
        }

    }
}
